package com.vt.common.security.component;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import com.vt.common.security.exception.*;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.stereotype.Component;


@Component("customWebResponseExceptionTranslator")
public class CustomWebResponseExceptionTranslator implements WebResponseExceptionTranslator {

    private final String[] whiteListURLs = {"org.springframework.security.oauth2.provider.endpoint.CheckTokenEndpoint"};

    @Override
    public ResponseEntity<OAuth2Exception> translate(Exception e) {

        String msg = e.getMessage();

        if (isWhiteURL(e.getClass().getName())
                || e.getCause() instanceof VerificationCodeFailException
                || e.getCause() instanceof UserDisabledException
                || e.getCause() instanceof UserNameNotFoundException
                || e.getCause() instanceof SocialAuthenticationException) {
        } else {
            msg = "用户名或密码错误";
        }
        return ResponseEntity
                .status(HttpStatus.HTTP_UNAUTHORIZED)
                .body(new CustomAuth2Exception(msg));
    }

    private boolean isWhiteURL(String clazz) {
        for (String whiteURL : whiteListURLs) {
            if (StrUtil.startWith(clazz, whiteURL)) {
                return true;
            }
        }
        return false;
    }
}
